package ant.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import ant.tools.PrintOut;

/**
 * 数据请求类，包含Get与Post两种请求，get请求通过参数辅助类{@link RequestHelper}的getParameter()
 * 来获取请求参数拼接URL，与post请求传入的参数一致，但具体处理方式不一样。
 * 
 * @author J.H
 *
 */
public class RequestServer {

	/**
	 * Get请求数据
	 * @param url  网络地址
	 * @return 请求后的数据
	 * @throws IOException IO流异常向外抛出
	 */
	public String get(ParameteInterface netParameter) throws IOException {
		StringBuffer buffer = new StringBuffer();
		String line = null;
		BufferedReader br = null;
		
		/*拼接Get请求URL*/
		StringBuilder builder=new StringBuilder();
		HashMap<String, String> parameters = netParameter.getParameter();
		for (Map.Entry<String, String> param : parameters.entrySet()) {
			if(builder.length()==0){
				builder.append(netParameter.getServerUrl());
				builder.append("?");
			}
			/*拼接请求参数*/
			builder.append("&");
			builder.append(param.getKey());
			builder.append("=");
			builder.append(param.getValue());
			PrintOut.info("Framework Parameter", param.getKey()+"="+param.getValue());
		}
		
		
		URL netUrl = new URL(builder.toString());
		HttpURLConnection connection = (HttpURLConnection) netUrl.openConnection();
		InputStream inputStream = connection.getInputStream();
		br = new BufferedReader(new InputStreamReader(inputStream));
		/*一行行循环读取字符*/
		while ((line = br.readLine()) != null) {
			buffer.append(line);
		}
		
		/*关闭流*/
		br.close();
		inputStream.close();
		
		/*打印请求来的信息*/
		PrintOut.info("Framework GET",buffer.toString());
		return buffer.toString();
	}

	
	
	
	/**
	 * post请求数据
	 * @param requestHelper 网络请求参数 
	 * @return 请求到的字符串
	 * @throws IOException  IO流异常向外抛出
	 * @throws ParseException  解析异常向外抛出
	 */
	public String post(RequestHelper requestHelper) throws ParseException, IOException {
		HttpPost httpPost=new HttpPost(requestHelper.getServerUrl());
		/*设置HttpPost头文件*/
		HashMap<String, String> headsMap = requestHelper.getHeads();
		for (Map.Entry<String, String> head : headsMap.entrySet()) {
			httpPost.setHeader(head.getKey(), head.getValue());
			PrintOut.info("Framework Heads", head.getKey()+"="+head.getValue());
		}
		
		BasicHttpParams httpParams=new BasicHttpParams();
		/*设置请求数据超时时间*/
		HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		
		/*将请求需要的参数放入集合中*/
		ArrayList<BasicNameValuePair> valuePairs=new ArrayList<BasicNameValuePair>();
		HashMap<String, String> parameters = requestHelper.getParameter();
		for (Map.Entry<String, String> param : parameters.entrySet()) {
			valuePairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
			PrintOut.info("Framework Parameter", param.getKey()+"="+param.getValue());
		}
		
		UrlEncodedFormEntity encodedFormEntity = null;
		try {
			/*设置请求的编码格式与请求参数*/
			encodedFormEntity=new UrlEncodedFormEntity(valuePairs,HTTP.UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			PrintOut.error("Framework UnsupportedEncodingException","不支持编码格式异常");
		}
		HttpClient httpClient=new DefaultHttpClient();
		/*将请求的参数与编码放入post请求中*/
		httpPost.setEntity(encodedFormEntity);
	
		/*执行请求*/
		HttpResponse response = httpClient.execute(httpPost);
		/*获取请求的数据转换得到字符串*/
		String string = EntityUtils.toString(response.getEntity());
		/*获取服务器所返回的头信息*/
		requestHelper.setHeaders(response.getAllHeaders());
		
		/*打印请求来的信息*/
		PrintOut.info("Framework POST",string);
		return string;
	}
	
}
